#!/bin/bash

SCRIPT_DIR="$(realpath "${0}")"
SCRIPT_DIR="$(dirname "${SCRIPT_DIR}")"
BUILD_DIR="${SCRIPT_DIR}/build"
VERSION="1.1.1"

# Build targets:
TARGET_FORMAT=no
TARGET_DIR=$BUILD_DIR
NO_ARGS=0

function print_usage() {
    cat <<EOF
    usage: $0 options
    This script build Programming in D in PDF and HTML format.
    OPTIONS:
    -f | --format	output format PDF or HTML or ALL
    -o | --out	    output folder for build artefact
    -h	Print this text
    build_book -fpdf
EOF
}

function parse_command_line() {
    VALID_OPTIONS=$(getopt -o f:d:hv --long format:,dir:,help,version -- "$@")

    eval set -- "$VALID_OPTIONS"

    while [ : ]; do
        case "$1" in
        -f | --format)
            echo "Output format is $2."
            if [[ "$2" =~ ^(pdf|html|all)$ ]]; then
                TARGET_FORMAT=$2
            else
                echo "Invalid target format $TARGET_FORMAT"
                exit 1
            fi
            echo $TARGET_FORMAT
            shift 2
            ;;
        -o | --out)
            echo "Output Folder is $2"
            TARGET_DIR=$2
            shift 2
            ;;
        -h | --help)
            print_usage
            exit 2
            ;;
        -v | --version)
            echo "Build script version $VERSION"
            exit 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Invalid option: $1"
            exit 1
            ;;
        esac
    done

}

function build_book_document() {
    local src_dir="${2}"
    local target_format="${1}"
    local target_dir="${3}"
    echo $src_dir

    if [[ $target_format == "html" || $target_format == "all" ]]; then
        echo "Building HTML"
        sphinx-build ${build_options} -b html "${src_dir}" "${target_dir}/html"
    fi
    if [[ $target_format == "pdf" || $target_format = "all" ]]; then
        echo "Building LaTeX and PDF"
        sphinx-build ${build_options} -b latex "${src_dir}" "${target_dir}/pdf"
        pushd "${BUILD_DIR}/pdf"
        latexmk -f -silent -pdf -dvi- -ps- *.tex || true
        mv *.pdf "${TARGET_DIR}"
        popd
    fi
}

if [ $# -eq $NO_ARGS ]; then
    echo "No argumentes were provided"
    print_usage
    exit 1
fi

parse_command_line "$@"
mkdir -p "${BUILD_DIR}"
mkdir -p "${TARGET_DIR}/html"
mkdir -p "${TARGET_DIR}/pdf"
if [[ $TARGET_FORMAT =~ "no" ]]
then
   echo "Target format was not set"
   exit
fi
build_book_document "$TARGET_FORMAT" "${SCRIPT_DIR}/source" "$TARGET_DIR"
echo "Build completed, please find documents in ${TARGET_DIR}"
